package com.yuan.pay_mall.service.impl;

import com.yuan.pay_mall.dao.UserMapper;
import com.yuan.pay_mall.enums.RoleEnum;
import com.yuan.pay_mall.pojo.User;
import com.yuan.pay_mall.service.IUserService;
import com.yuan.pay_mall.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

import static com.yuan.pay_mall.enums.ResponseEnum.*;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 注册
     * 测试方法：
     * 选中方法名，右键goto--->Test-->Create new Test---junit4  勾选方法
     * @param user
     */
    @Override
    public ResponseVo<User> register(User user) {
        //error();//模拟错误
        //username不能重复
        int countByUsername = userMapper.countByUsername(user.getUsername());
        if(countByUsername >0){
           // throw new RuntimeException("该名字已经注册");
            return ResponseVo.error(USERNAME_EXIST);
        }
        int countByEmail = userMapper.countByEmail(user.getEmail());
        if(countByEmail >0){
           // throw new RuntimeException("该邮箱已经注册");
            return ResponseVo.error(EMAIL_EXIST);
        }
        //添加角色
        user.setRole(RoleEnum.CUSTOMER.getCode());
        //MD5摘要算法(Spring自带的)
        user.setPassword(DigestUtils.md5DigestAsHex(
                user.getPassword().getBytes(StandardCharsets.UTF_8))
        );
        log.info("user.getPassword()={}",user.getPassword());
        //写入数据库
        int resultCount = userMapper.insertSelective(user);
        if(resultCount == 0){
            //throw new RuntimeException("注册失败");
            return ResponseVo.error(ERROR);
        }
        return ResponseVo.success();
    }

    @Override
    public ResponseVo<User> login(String username, String password) {
        User user = userMapper.selectByUsername(username);
        //判断用户是否存在，null则没有这个用户
        if(user == null){
            //用户不存在(返回：用户名或密码错误)
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }

        //如果密码不相等，返回错误
        if(!user.getPassword().equalsIgnoreCase(
                DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))){
            //密码错误(返回：用户名或密码错误)
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }
       log.info("user.getPassword()={}",user.getPassword());
        user.setPassword("");//这里置空，postman就看不到了
        return ResponseVo.success(user);

    }

    //模拟错误
    private void error(){
        throw new RuntimeException("意外错误");
    }

}


